// 1. 引入依赖模块
const http = require('http')
const url = require('url')
const fs = require('fs')
const users = require('./user.json')

// 2. 创建服务器
const server = http.createServer((req, res) => {
  res.setHeader('Content-Type', "text/html;charset=utf-8")
  let obj = url.parse(req.url, true).query;
  if (Object.keys(obj).length > 0) {
    let resObj = render(obj)
    res.write(resObj)
    res.end()
  }
  res.end()
})

// 3.封装渲染函数
function render (data) {
  // 对数据进行解构赋值
  const { username = '', pwd = '' } = data
  if (!username && !pwd) {
    return `<span> 你输入的用户名和密码错误!! </span>`
  }
  users.push({
    username,
    pwd
  })
  fs.writeFileSync('./user.json', JSON.stringify(users))

  return `成功!`
}

// 启动服务器
server.listen(8989, () => {
  console.log('http://127.0.0.1:8989');
})